import React, { useState, useEffect } from 'react';
import {
  Modal,
  Table,
  Card,
  Statistic,
  Row,
  Col,
  Typography,
  Tag,
  Tabs,
  Progress,
  Space,
  Divider,
  Spin,
  message
} from 'antd';
import {
  TeamOutlined,
  BarChartOutlined,
  UserOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import { directoryApi } from '../services/api';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface TeamDistributionData {
  team_name: string;
  total_count: number;
  uma_metrics: number;
  ukm_metrics: number;
  metric_types: {
    histogram: number;
    enum: number;
    ukm_event: number;
    ukm_metric: number;
    unknown: number;
  };
  assignment_confidence: number;
  last_assigned: string | null;
}

interface TeamDistributionResponse {
  directory_path: string;
  directory_name: string;
  total_metrics: number;
  teams: TeamDistributionData[];
  unassigned_count: number;
  uma_summary: {
    total: number;
    teams: Record<string, number>;
  };
  ukm_summary: {
    total: number;
    teams: Record<string, number>;
  };
}

interface TeamDistributionModalProps {
  visible: boolean;
  onClose: () => void;
  directoryId: number;
  directoryPath: string;
}

const TeamDistributionModal: React.FC<TeamDistributionModalProps> = ({
  visible,
  onClose,
  directoryId,
  directoryPath
}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<TeamDistributionResponse | null>(null);

  useEffect(() => {
    if (visible && directoryId) {
      loadTeamDistribution();
    }
  }, [visible, directoryId]);

  const loadTeamDistribution = async () => {
    try {
      setLoading(true);
      const response = await directoryApi.getDirectoryTeamDistribution(directoryId);
      if (response.success) {
        setData(response.data);
      } else {
        message.error('获取团队分布数据失败');
      }
    } catch (error) {
      console.error('Failed to load team distribution:', error);
      message.error('获取团队分布数据失败');
    } finally {
      setLoading(false);
    }
  };

  const teamColumns = [
    {
      title: '团队名称',
      dataIndex: 'team_name',
      key: 'team_name',
      render: (teamName: string) => (
        <Space>
          <TeamOutlined style={{ color: '#1890ff' }} />
          <Text strong>{teamName}</Text>
        </Space>
      ),
    },
    {
      title: '总遥测点数',
      dataIndex: 'total_count',
      key: 'total_count',
      render: (count: number) => (
        <Tag color="blue" style={{ fontSize: '14px', padding: '4px 8px' }}>
          {count.toLocaleString()}
        </Tag>
      ),
      sorter: (a: TeamDistributionData, b: TeamDistributionData) => a.total_count - b.total_count,
    },
    {
      title: 'UMA遥测点',
      dataIndex: 'uma_metrics',
      key: 'uma_metrics',
      render: (count: number, record: TeamDistributionData) => (
        <Space direction="vertical" size="small" style={{ width: '100%' }}>
          <Tag color="green" style={{ fontSize: '12px' }}>
            {count.toLocaleString()}
          </Tag>
          <div style={{ fontSize: '11px', color: '#666' }}>
            直方图: {record.metric_types.histogram} | 枚举: {record.metric_types.enum}
          </div>
        </Space>
      ),
    },
    {
      title: 'UKM遥测点',
      dataIndex: 'ukm_metrics',
      key: 'ukm_metrics',
      render: (count: number, record: TeamDistributionData) => (
        <Space direction="vertical" size="small" style={{ width: '100%' }}>
          <Tag color="orange" style={{ fontSize: '12px' }}>
            {count.toLocaleString()}
          </Tag>
          <div style={{ fontSize: '11px', color: '#666' }}>
            事件: {record.metric_types.ukm_event} | 指标: {record.metric_types.ukm_metric}
          </div>
        </Space>
      ),
    },
    {
      title: '占比',
      key: 'percentage',
      render: (record: TeamDistributionData) => {
        const percentage = data ? (record.total_count / data.total_metrics) * 100 : 0;
        return (
          <Progress
            percent={percentage}
            size="small"
            format={(percent) => `${percent?.toFixed(1)}%`}
            strokeColor="#1890ff"
          />
        );
      },
    },
  ];

  const renderSummaryCards = () => {
    if (!data) return null;

    return (
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总遥测点数"
              value={data.total_metrics}
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已分配团队"
              value={data.total_metrics - data.unassigned_count}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="未分配团队"
              value={data.unassigned_count}
              prefix={<CloseCircleOutlined />}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="团队数量"
              value={data.teams.length}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>
    );
  };

  const renderUMAUKMBreakdown = () => {
    if (!data) return null;

    return (
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title={<><Text style={{ color: '#52c41a' }}>UMA 遥测点分布</Text></>}>
            <div style={{ marginBottom: 16 }}>
              <Text strong>总计: {data.uma_summary.total.toLocaleString()}</Text>
            </div>
            {Object.entries(data.uma_summary.teams).map(([team, count]) => (
              <div key={team} style={{ marginBottom: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>{team}</Text>
                  <Tag color="green">{count.toLocaleString()}</Tag>
                </div>
                <Progress
                  percent={(count / data.uma_summary.total) * 100}
                  size="small"
                  showInfo={false}
                  strokeColor="#52c41a"
                />
              </div>
            ))}
          </Card>
        </Col>
        <Col span={12}>
          <Card title={<><Text style={{ color: '#fa8c16' }}>UKM 遥测点分布</Text></>}>
            <div style={{ marginBottom: 16 }}>
              <Text strong>总计: {data.ukm_summary.total.toLocaleString()}</Text>
            </div>
            {Object.entries(data.ukm_summary.teams).map(([team, count]) => (
              <div key={team} style={{ marginBottom: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>{team}</Text>
                  <Tag color="orange">{count.toLocaleString()}</Tag>
                </div>
                <Progress
                  percent={(count / data.ukm_summary.total) * 100}
                  size="small"
                  showInfo={false}
                  strokeColor="#fa8c16"
                />
              </div>
            ))}
          </Card>
        </Col>
      </Row>
    );
  };

  return (
    <Modal
      title={
        <Space>
          <TeamOutlined />
          <span>团队分布列表 - {directoryPath}</span>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={1000}
      footer={null}
      destroyOnClose
    >
      <Spin spinning={loading}>
        {data && (
          <div>
            {renderSummaryCards()}

            <Tabs defaultActiveKey="1">
              <TabPane tab="团队详情" key="1">
                <Table
                  columns={teamColumns}
                  dataSource={data.teams}
                  rowKey="team_name"
                  pagination={false}
                  size="middle"
                  scroll={{ x: 800 }}
                />
              </TabPane>
              <TabPane tab="UMA/UKM分布" key="2">
                {renderUMAUKMBreakdown()}
              </TabPane>
            </Tabs>

            {data.unassigned_count > 0 && (
              <>
                <Divider />
                <div style={{ textAlign: 'center', color: '#666' }}>
                  <Text>
                    还有 {data.unassigned_count.toLocaleString()} 个遥测点未分配给任何团队
                  </Text>
                </div>
              </>
            )}
          </div>
        )}
      </Spin>
    </Modal>
  );
};

export default TeamDistributionModal;